package com.qdd01.controller;

import com.qdd01.Async.AsyncService;
import com.qdd01.entity.Dto.CommentDto;
import com.qdd01.entity.Dto.CommentQuerDto;
import com.qdd01.service.CommentService;
import com.qdd01.util.BaseContext;
import com.qdd01.util.PageResult;
import com.qdd01.util.Result;
import com.qdd01.websocket.WebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private UserService userService; // 注入UserService

    /**
     * 添加评论
     */
    @PostMapping("addComment")
    public Result addComment(@RequestBody CommentDto commentDto) {
        // 获取当前用户ID
        Integer userId = BaseContext.getCurrentId();
        // 获取用户信息
        User user = userService.getById(userId);
        
        // 补充评论数据
        commentDto.setUserId(userId);
        commentDto.setUsername(user.getUsername());
        commentDto.setUserAvatar(user.getPic());
        
        // 如果是回复，补充被回复用户的信息
        if (commentDto.getParentId() != null && commentDto.getReplyUserId() != null) {
            User replyToUser = userService.getById(commentDto.getReplyUserId());
            commentDto.setReplyUsername(replyToUser.getUsername());
        }

        // 保存评论并获取返回的评论ID
        CommentDto savedComment = asyncService.addComment(commentDto);
        
        // 使用保存后的评论（包含ID）进行广播
        WebSocketHandler.broadcastComment(commentDto.getVideoId(), savedComment);
        
        return Result.success(savedComment); // 返回保存后的评论
    }

    /**
     * 获取评论
     */
    @PostMapping("getComment")
    public Result<PageResult> getComment(@RequestBody CommentQuerDto commentQuerDto) {
        commentQuerDto.setUserId(BaseContext.getCurrentId());
        PageResult pageResult = commentService.getComment(commentQuerDto);
        return Result.success(pageResult);
    }

    /**
     * 删除评论
     */
    @PostMapping("del/{id}")
    public Result del(@PathVariable Integer id) {
        // 获取当前用户ID
        Integer userId = BaseContext.getCurrentId();
        
        // 检查评论是否存在
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return Result.error("评论不存在");
        }
        
        // 检查是否有权限删除（只能删除自己的评论，或者是管理员）
        User currentUser = userService.getById(userId);
        if (!comment.getUserId().equals(userId) && currentUser.getRoleId() != 1) {
            return Result.error("没有权限删除此评论");
        }
        
        // 删除评论
        boolean success = asyncService.del(id);
        if (success) {
            // 如果是回复，更新父评论的回复数
            if (comment.getParentId() != null) {
                commentService.updateReplyCount(comment.getParentId());
            }
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
} 